package com.example.trans.service.impl;

import com.example.trans.dao.AccountDao;
import com.example.trans.pojo.Account;
import com.example.trans.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * ClassName:AccountServiceImpl
 * Package:com.example.trans.service.impl
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/5/11-10:39
 * @Version:v1.0
 */
@Service("accountService")
@Transactional(isolation = Isolation.READ_COMMITTED )//开启事务
public class AccountServiceImpl implements AccountService {

    @Resource(name = "accountDao")
    private AccountDao accountDao;

    //控制事务
    @Override
//    @Transactional//开启事务
    public void transfer(String fromActno, String toActno, double money) {
        //查询转出账户余额是否足够
        Account fromAct = accountDao.selectByActon(fromActno);
        if (fromAct.getBalance() < money) {
            throw new RuntimeException("余额不足");
        }
        //余额充足
        Account toAct = accountDao.selectByActon(toActno);

        //将内存中两个对象的余额进行修改
        fromAct.setBalance(fromAct.getBalance() - money);
        toAct.setBalance(toAct.getBalance() + money);
        //数据库更新
        int count = accountDao.update(fromAct);
//        //模拟异常
//        String s = null;
//        s.toString();

        count += accountDao.update(toAct);

        if (count != 2) {
            throw new RuntimeException("转账失败,联系银行");
        }

        //提交事务

        //事务回滚
    }

    @Transactional()
    public void withdraw(){

    }


    @Resource(name = "accountService2")
    private AccountService accountService;
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void save(Account act) {

        //调用Dao中的
        accountDao.insert(act);
        //创建账户对象
        Account act2 = new Account("act-004",1000.0);
        try {
            accountService.save(act2);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
